package com.bolun998300.personal_blog_springboot.controller.background;

import com.bolun998300.personal_blog_springboot.Utils.IpUtil;
import com.bolun998300.personal_blog_springboot.Utils.Result;
import com.bolun998300.personal_blog_springboot.pojo.Blog;
import com.bolun998300.personal_blog_springboot.pojo.Comment;
import com.bolun998300.personal_blog_springboot.service.BlogService;
import com.bolun998300.personal_blog_springboot.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@RestController
public class CommentController {

    @Autowired
    private CommentService commentService;
    @Autowired
    private BlogService blogService;

    @GetMapping(value = "/comments/listByPage/{operate}")
    public HashMap<String,Object> listByPage(int page , int limit, @PathVariable String operate){
        Page<Comment> pageFromJpa = commentService.listByPage(page,limit,operate);
        List<Comment> list = pageFromJpa.getContent();
        for(Comment bean : list){
            bean.setBlogTitle(blogService.get(bean.getBlogId()).getTitle());
        }
        HashMap<String,Object> map = new HashMap<>();
        map.put("code",0);
        map.put("msg","");
        map.put("count",pageFromJpa.getTotalElements());
        map.put("data",pageFromJpa.getContent());
        return map;
    }

    @PutMapping(value = "/comments/{operate}")
    public Object update(@PathVariable String operate, HttpServletRequest request){
        String[] ids = request.getParameterValues("ids");
        for(int i = 0;i < ids.length;i++){
            int id = Integer.parseInt(ids[i]);
            Comment comment = commentService.get(id);
            if("commentIsNotPass".equals(operate)){
                comment.setState(-1);
            }else {
                comment.setState(1);
                Blog blog = blogService.get(comment.getBlogId());
                blog.setReplyHit(blog.getReplyHit()+1);
                blogService.update(blog);
            }
            comment.setUpdateTime(new Date());
            commentService.update(comment);
        }
        return Result.success();
    }


    @PostMapping("/comments")
    public Object saveComment(@RequestBody Comment comment,HttpServletRequest request){
        String userIp=IpUtil.getIpAddr(request);
        comment.setUserIp(userIp);
        comment.setCommentDate(new Date());
        comment.setCreateTime(new Date());
        comment.setState(0);
        commentService.save(comment);
        return Result.success(comment);
    }

    @GetMapping("/comments/{id}")
    public Object getCommentsByBlogId(@PathVariable int id){
        List<Comment> commentList = commentService.getCommentsByBlogId(id);

        return commentList;
    }




}
